import { defineStore } from "pinia";
import { getToken, setToken, removeToken } from '@/utils/cookie'
import { loginApi,logoutApi,getUserInfoApi } from '@/api/auth'

export const useAuthStore = defineStore('auth', {
    state: () => ({
        userInfo: sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : null,
        webSiteInfo: {
            aliPay: '',
            weixinPay: ''
        },
        token: getToken() || '',
        searchVisible: false,
        mobileMenuVisible: false,
        visitorAccess: 0,
        siteAccess: 0,
        isLoading: false,
        notice: null,
        isUnread: false,
    }),
    actions: {
        setSiteInfo(info) {
            this.webSiteInfo = info
        },
        setUserInfo(userInfo) {
            this.userInfo = userInfo
            sessionStorage.setItem("user", JSON.stringify(userInfo))
        },
        setToken(token){
            setToken(token)
        },
        setMobileMenuVisible(visible) {
            this.mobileMenuVisible = visible;
        },
        setSearchVisible(visible) {
            this.searchVisible = visible
        },
        /**
         * 登录
         */
        async loginAction(loginData) {
            try {
                const res = await loginApi(loginData)
                if (res.data) {
                    setToken(res.data.token)
                    this.setUserInfo(res.data)
                    return Promise.resolve(res)
                }
                return Promise.reject(res)
            } catch (error) {
                return Promise.reject(error)
            }
        },
        async logout() {
            await logoutApi();
            removeToken();
            this.setUserInfo(null); // 调用mutations中定义的方法
        }
    }
})